package com.psbc.springbootstudydemo1.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.psbc.springbootstudydemo1.domain.User;
import com.psbc.springbootstudydemo1.service.UserService;
import com.psbc.springbootstudydemo1.service.impl.UserServiceImpl;
import com.psbc.springbootstudydemo1.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(urlPatterns = "/api/v1/pri/order/*",filterName = "loginFilter")
public class LoginFilter implements Filter {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter init=================");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter loginFilter===========");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)) {
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                JsonData jsonData = JsonData.buildError("登录失败，token无效", -2);
                String s = objectMapper.writeValueAsString(jsonData);
                renderJson(rep,s);
            }
        } else {
            JsonData jsonData = JsonData.buildError("未登录", -3);
            String s = objectMapper.writeValueAsString(jsonData);
            renderJson(rep,s);
        }
    }

    @Override
    public void destroy() {
        System.out.println("filter destroy==============");
    }

    private void renderJson(HttpServletResponse resp, String json) {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        try (PrintWriter writer = resp.getWriter()) {
            writer.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
